<template>
	<view class="container">
		<!-- 记录筛选 -->
		<view class="filter-tabs">
			<view 
				v-for="tab in tabs" 
				:key="tab.value"
				class="tab-item"
				:class="{ active: currentTab === tab.value }"
				@click="currentTab = tab.value"
			>
				{{ tab.label }}
			</view>
		</view>

		<!-- 记录列表 -->
		<view class="records-list">
			<!-- 加载中的骨架屏 -->
			<template v-if="loading">
				<view class="record-item" v-for="i in 10" :key="i">
					<view class="record-header">
						<view class="skeleton-bar-short"></view>
						<view class="skeleton-bar-short"></view>
					</view>
					<view class="record-body">
						<view class="skeleton-bar"></view>
						<view class="skeleton-bar"></view>
						<view class="skeleton-bar"></view>
					</view>
				</view>
			</template>

			<view 
				v-for="(record, index) 
				in filteredRecords" 
				:key="index"
				class="record-item"
				v-else
			>
				<view class="record-header">
					<text class="record-type">{{ record.description || '借款' }}</text>
					<view class="record-status" :class="statusMap[record.status]">
						<text>{{ statusMap[record.status] }}</text>
						<view class="status-light"></view>
					</view>
				</view>
				<view class="record-body">
					<view class="amount">
						<text>金额</text>
						<text class="amount-plus">
							¥{{ record.amount }}
						</text>
					</view>
					<view class="date">
						<text>申请日期</text>
						<text>{{ record.create_time || '未知' }}</text>
					</view>
					<!-- 只有已放款(3)和已逾期(5)的才显示还款日期和期限 -->
					<template v-if="[3, 5].includes(record.status)">
					<view class="date">
						<text>还款日期</text>
						<text>{{ record.repayment_time || '未知' }}</text>
					</view>
					<view class="term">
						<text>期限</text>
						<text :class="{ 'overdue-days': record.loan_time < 0 }">
							{{ Math.abs(record.loan_time) }}天{{ record.loan_time < 0 ? '(已逾期)' : '' }}
						</text>
					</view>
					</template>
					<view class="overdue" v-if="record.overdue_days">
						<text>逾期天数</text>
						<text class="overdue-days">{{ record.overdue_days }}天</text>
					</view>
					<view class="overdue" v-if="record.overdue_amount">
						<text>逾期费用</text>
						<text class="overdue-amount">¥{{ record.overdue_amount }}</text>
					</view>
					<view class="remaining-days" v-if="[3, 5].includes(record.status)">
						<text>距还款</text>
						<text :class="{
							'warning': record.remaining_days <= 3 && record.remaining_days > 0,
							'expired': record.remaining_days <= 0,
							'normal': record.remaining_days > 3
						}">
							{{ 
								record.remaining_days > 0 
								? `还有${record.remaining_days}天` 
								: record.remaining_days === 0
								? '今天到期'
								: `已逾期${Math.abs(record.remaining_days)}天`
							}}
						</text>
					</view>
				</view>
			</view>
			
			<view v-if="filteredRecords.length === 0" class="empty-tip">
				暂无记录
			</view>
			
			<!-- 加载状态提示 -->
			<view v-if="hasMore" class="loading-more">
				<text>上拉加载更多</text>
			</view>
			<view v-else class="loading-more">
				<text>没有更多数据了</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { STORAGE_KEY } from '../../common/config';
import request from "@/common/request.js"
const currentTab = ref('all')
const records = ref([])
const pageSize = 10
const currentPage = ref(1)
const hasMore = ref(true)
const isLoading = ref(false)
const loading = ref(true)

const tabs = [
	{ label: '全部', value: 'all' },
	{ label: '借款', value: 'loan' },
	{ label: '还款', value: 'repay' }
]

// 修改状态映射
const statusMap = {
	0: '待审核',
	1: '已通过',
	2: '已拒绝',
	3: '已放款',
	4: '已还款',
	5: '已逾期',
	6: '已流标'
}

// 根据标签筛选记录
const filteredRecords = computed(() => {
	if (currentTab.value === 'all') return records.value
	return records.value.filter(record => 
		(currentTab.value === 'loan' && [0, 1, 3, 5].includes(record.status)) ||
		(currentTab.value === 'repay' && record.status === 4)
	)
})

// 计算时间差函数
const calculateDaysDiff = (startDate, endDate) => {
	if (!startDate || !endDate) return 0
	// 标准化日期到0点
	const start = new Date(startDate)
	start.setHours(0, 0, 0, 0)
	const end = new Date(endDate)
	end.setHours(0, 0, 0, 0)
	const now = new Date()
	now.setHours(0, 0, 0, 0)
	
	// 如果当前日期超过还款日期，返回负数表示逾期天数
	if (now > end) {
		const diffTime = end - now
		return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
	}
	
	// 否则返回正常的借款期限
	const diffTime = end - start
	const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
	return diffDays
}

// 计算距离还款日的剩余天数
const calculateRemainingDays = (endDate) => {
	if (!endDate) return null
	const end = new Date(endDate)
	end.setHours(0, 0, 0, 0)
	const now = new Date()
	now.setHours(0, 0, 0, 0)
	const diffTime = end - now
	const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
	return diffDays
}

// 计算期限天数
const calculateLoanDays = (repaymentTime) => {
	if (!repaymentTime) return 0
	const today = new Date()
	today.setHours(0, 0, 0, 0)
	
	const repayDate = new Date(repaymentTime)
	repayDate.setHours(0, 0, 0, 0)
	
	const diffTime = repayDate - today
	const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
	
	return Math.abs(diffDays)
}

// 分页加载记录
const loadMoreRecords = () => {
	if (isLoading.value) return
	isLoading.value = true
	loading.value = true
	
	setTimeout(() => {
		const storageRecords = uni.getStorageSync(STORAGE_KEY.LOAN_RECORDS)
		if (storageRecords) {
			try {
				const parsedData = JSON.parse(storageRecords)
				const allRecords = Array.isArray(parsedData) ? parsedData : []
				
				// 计算每条记录的借款天数和剩余天数
				const recordsWithDays = allRecords.map(record => ({
					...record,
					loan_time: calculateDaysDiff(record.loan_time, record.repayment_time),
					remaining_days: calculateRemainingDays(record.repayment_time)
				}))
				
				const start = (currentPage.value - 1) * pageSize
				const end = start + pageSize
				const newRecords = recordsWithDays.slice(start, end)
				
				if (currentPage.value === 1) {
					records.value = newRecords
				} else {
					records.value = [...records.value, ...newRecords]
				}
				
				hasMore.value = end < recordsWithDays.length
			} catch (error) {
				console.error('解析记录数据失败:', error)
				records.value = []
				hasMore.value = false
			}
		}
		
		isLoading.value = false
		loading.value = false
	}, 1000)
}

// 下拉刷新
const onPullDownRefresh = () => {
	currentPage.value = 1
	loadMoreRecords()
	uni.stopPullDownRefresh()
}

// 上拉加载更多
const onReachBottom = () => {
	if (hasMore.value) {
		currentPage.value++
		loadMoreRecords()
	}
}

// 查询我的订单
const get_my_order = () => {
	request.get("api/loan/select/my_order/").then(res => {
		uni.setStorageSync(STORAGE_KEY.LOAN_RECORDS, JSON.stringify(res.data))
	})
}

// 添加状态说明
const getStatusDescription = (status) => {
	switch(status) {
		case 0: return '等待审核中'
		case 1: return '审核已通过'
		case 2: return '审核未通过'
		case 3: return '已成功放款'
		case 4: return '已完成还款'
		case 5: return '已逾期未还'
		case 6: return '已流标'
		default: return '未知状态'
	}
}

onMounted(() => {
	get_my_order()
	loadMoreRecords()
})
</script>

<style lang="scss" scoped>
.container {
	background-color: #f5f7fa;
	min-height: 100vh;
}

.filter-tabs {
	display: flex;
	background-color: #fff;
	padding: 20rpx 30rpx;
	margin-bottom: 20rpx;
	position: sticky;
	top: 0;
	z-index: 100;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		padding: 15rpx 0;
		position: relative;
		transition: all 0.3s;
		
		&.active {
			color: #4A90E2;
			font-weight: bold;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 40rpx;
				height: 4rpx;
				background-color: #4A90E2;
				border-radius: 2rpx;
				animation: slideIn 0.3s ease-out;
			}
		}
	}
}

@keyframes slideIn {
	from {
		width: 0;
		opacity: 0;
	}
	to {
		width: 40rpx;
		opacity: 1;
	}
}

.records-list {
	padding: 30rpx;
	
	.record-item {
		background: linear-gradient(135deg, #fff, #f8f9fa);
		border: 1px solid rgba(74,144,226,0.1);
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		transform: translateY(0);
		transition: all 0.3s;
		box-shadow: 0 4rpx 20rpx rgba(74,144,226,0.08);
		
		&:active {
			transform: translateY(2rpx);
			box-shadow: 0 2rpx 10rpx rgba(74,144,226,0.05);
		}
		
		.record-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;
			
			.record-type {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.record-status {
				position: relative;
				padding: 6rpx 20rpx;
				border-radius: 30rpx;
				font-weight: 500;
				overflow: hidden;
				display: flex;
				align-items: center;
				
				text {
					position: relative;
					z-index: 1;
					font-size: 26rpx;
				}
				
				.status-light {
					position: absolute;
					top: -50%;
					right: -50%;
					width: 100%;
					height: 100%;
					background: radial-gradient(circle, rgba(255,255,255,0.8) 0%, transparent 70%);
					animation: rotate 4s linear infinite;
					z-index: 0;
				}
				
				&.待审核 {
					color: #faad14;
					background: linear-gradient(45deg, rgba(250,173,20,0.1), rgba(250,173,20,0.2));
				}
				
				&.已通过 {
					color: #1890ff;
					background: linear-gradient(45deg, rgba(24,144,255,0.1), rgba(24,144,255,0.2));
				}
				
				&.已放款 {
					color: #52c41a;
					background: linear-gradient(45deg, rgba(82,196,26,0.1), rgba(82,196,26,0.2));
				}
				
				&.已还款 {
					color: #13c2c2;
					background: linear-gradient(45deg, rgba(19,194,194,0.1), rgba(19,194,194,0.2));
				}
				
				&.已逾期 {
					color: #ff4d4f;
					background: linear-gradient(45deg, rgba(255,77,79,0.1), rgba(255,77,79,0.2));
				}
				
				&.已拒绝 {
					color: #ff4d4f;
					background: linear-gradient(45deg, rgba(255,77,79,0.1), rgba(255,77,79,0.2));
				}
				
				&.已流标 {
					color: #faad14;
					background-color: rgba(250, 173, 20, 0.1);
				}
				
				.status-desc {
					position: absolute;
					top: 100%;
					right: 0;
					font-size: 22rpx;
					color: #999;
					margin-top: 4rpx;
					white-space: nowrap;
				}
			}
		}
		
		.record-body {
			view {
				display: flex;
				justify-content: space-between;
				margin-bottom: 10rpx;
				
				text:first-child {
					color: #999;
					font-size: 26rpx;
				}
				
				text:last-child {
					color: #333;
					font-size: 26rpx;
				}
				
				&.amount {
					text:last-child {
						position: relative;
						padding: 4rpx 16rpx;
						border-radius: 8rpx;
						background: linear-gradient(135deg, rgba(74,144,226,0.1), rgba(135,206,235,0.1));
						
						&.amount-plus {
							color: #1890ff;
							font-size: 36rpx;
						}
						
						&.amount-minus {
							color: #FF6B6B;
							background: linear-gradient(45deg, #FF6B6B, #FFA07A);
							-webkit-background-clip: text;
							-webkit-text-fill-color: transparent;
						}
					}
				}
			}
		}
	}
	
	.empty-tip {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 100rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		
		&::before {
			content: '📝';
			font-size: 80rpx;
			margin-bottom: 20rpx;
		}
	}
	
	.loading-more {
		text-align: center;
		color: #999;
		font-size: 28rpx;
		padding: 40rpx 0;
		position: relative;
		
		&::after {
			content: '';
			position: absolute;
			left: 50%;
			bottom: 20rpx;
			transform: translateX(-50%);
			width: 100rpx;
			height: 4rpx;
			background: linear-gradient(90deg, transparent, #999, transparent);
		}
	}
}

.overdue-days,
.overdue-amount {
	color: #ff4d4f !important;
	font-weight: bold;
}

.record-body {
	.order-number {
		text:last-child {
			font-family: monospace;
			font-size: 24rpx;
			color: #666;
		}
	}
}

.remaining-days {
	text:last-child {
		font-weight: bold;
		
		&.warning {
			color: #ff4d4f !important;
		}
		
		&.expired {
			color: #ff4d4f !important;
		}
		
		&.normal {
			color: #52c41a !important;
		}
	}
}

@keyframes rotate {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}
</style> 